from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SPU, SPUSpecification
from apps.meiduo_admin.serializers import SPUSerializer, SPUSpecsSerializer
from apps.meiduo_admin.utils import CurPagination


class SPUView(ModelViewSet):
    permission_classes = [IsAdminUser]
    lookup_field = 'id'
    lookup_value_regex = '\d+'
    queryset = SPU.objects.all().order_by('id')
    serializer_class = SPUSerializer
    pagination_class = CurPagination

    def images(self, request):
        image = request.FILES.get('image')
        if image:
            client = Fdfs_client(settings.FDFS_CONF)
            upload_ret = client.upload_by_buffer(image.read())
            if upload_ret['Status'] == 'Upload successed.':
                img_url = settings.FDFS_BASE_URL + upload_ret['Remote file_id']
                print(img_url)
                return Response({'img_url': img_url})
        # 上传失败
        return Response(status=status.HTTP_403_FORBIDDEN)


class SPUSpecsViews(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request, pk):
        queryset = SPUSpecification.objects.filter(spu_id=pk)
        ser = SPUSpecsSerializer(queryset, many=True)
        return Response(ser.data)
